package com.tangding.service.dao.user;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.bson.Document;
import org.springframework.stereotype.Repository;

import com.tangding.common.exception.GException;
import com.tangding.common.logx.LogHelp;
import com.tangding.service.db.BaseMongoRepository;
import com.tangding.service.db.MongoDBOption;
import com.tangding.service.entity.user.LoginCache;

/**
 * @description 
 *
 * @author Ranger
 * @version 2018年1月5日_下午5:28:26
 *
 */
@Repository
public class LoginRepository extends BaseMongoRepository<LoginCache, Serializable>{
	private static Map<String, String> loginCache = new ConcurrentHashMap<>();
	@Override
	protected void afterInitClient() {
		option = new MongoDBOption("ACCOUNT", "loginCache");
		
		try {
			List<LoginCache> all = findAll();
			if (all != null && all.size() > 0) {
				all.forEach(cache -> {
					loginCache.put(cache.getUid(), cache.getAccessToken());
				});
			}
		} catch (GException e) {
			LogHelp.doLogException(e);
			System.exit(-1);
		}
	}
	
	public void push(String uid, String accessToken) {
		loginCache.put(uid, accessToken);
		LoginCache cache = new LoginCache();
		cache.setUid(uid);
		cache.setAccessToken(accessToken);
		Document condition = new Document();
		condition.put("uid", uid);
		update(cache, condition);
	}
	
	public String get(String uid) {
		return loginCache.get(uid);
	}
}
